package pl.nazaweb.utils.restpojomaper;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author naza - Marek Kawczyński
 */
public class MapperDispatcher {

    private PojoAutoMapper pojoAutoMapper;

    public MapperDispatcher(PojoAutoMapper pojoAutoMapper) {
        this.pojoAutoMapper = pojoAutoMapper;
    }

    public Object pojoMapper(Object listToMap, String method) {
        List result = new ArrayList();
        for (Object entity : (List) listToMap) {
            if (getPojoAutoMapper().getParameterizedClass().isInstance(entity)) {
                Object pojo = getPojoFromEntity(entity, method);
                result.add(pojo);
            }
        }
        return result;
    }

    public Object mapMapper(Object listToMap, String methodName) {
        String keyMethod = getPojoAutoMapper().getMapAsMapKeyMethod(methodName);
        String valueMethod = getPojoAutoMapper().getMapAsMapValueMethod(methodName);
        Map<Object, Object> result = new HashMap();
        try {
            for (Object entity : (List) listToMap) {
                Method keyGetter = entity.getClass().getMethod(keyMethod, new Class[]{});
                Method valueGetter = entity.getClass().getMethod(valueMethod, new Class[]{});
                Object key = keyGetter.invoke(entity);
                Object value = valueGetter.invoke(entity);
                result.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private Object getPojoFromEntity(Object entity, String calledMethodName) throws SecurityException {
        Object pojo = getPojoAutoMapper().newPojoInstance(calledMethodName);
        for (Method pojoMethod : pojo.getClass().getDeclaredMethods()) {
            String methodName = pojoMethod.getName();
            if (methodName.substring(0, 3).equals("set")) {
                fillPojoPropertyWithEntityProperty(methodName, entity, pojoMethod, pojo);
            }
        }
        return pojo;
    }

    private void fillPojoPropertyWithEntityProperty(String methodName, Object entity, Method pojoMethod, Object pojo) {
        try {
            methodName = methodName.replace("set", "get");
            Method entityGetter = entity.getClass().getMethod(methodName, new Class[]{});
            Object value = entityGetter.invoke(entity);
            pojoMethod.invoke(pojo, value);
        } catch (Exception ex) {
        }
    }

    public PojoAutoMapper getPojoAutoMapper() {
        return pojoAutoMapper;
    }

    public void setPojoAutoMapper(PojoAutoMapper pojoAutoMapper) {
        this.pojoAutoMapper = pojoAutoMapper;
    }
}
